//
//  CreateItemVC.swift
//  物料商行
//
//  Created by HaoDong Hong on 2017/9/13.
//  Copyright © 2017年 HaoDong Hong. All rights reserved.
//

import UIKit
import SCLAlertView
import SwiftyJSON
import SVProgressHUD

protocol CreateItemDelegate: class {
    func didCreateItem(material: Material)
}
class CreateItemVC: UITableViewController {
    var classId: Int!

    var listsTitle = [["名称", "种类", "货号", "单价", "单位"], [nil], [""], [""], [""], [""]]

    /// Section zero and Section one values, 其中listsValue[0][1] 指的是styleId, 没有保存在这里，保存在nextStyle
    var listsValue: [[String?]] = [[nil, nil, nil, nil, nil], [nil]]

    /// Section two values 色板图片
    var colorLists = [CodableColorOfMaterial]()

    /// Section three values
    var componentLists = [CodableComponentOfMaterial]()

    /// Section four value
    var materialImage: UIImage!

    /// Section five value
    var pictures = [CodablePictureOfMaterial]()

    var keyBoardTypes: [UIKeyboardType?] = [.default, nil, .numberPad, .numberPad, .default]

    var placeHolder = ["请输入面料名称", nil,  "请输入货号", "请输入单价", "请输入单位"]
    let sectionTitles = [nil, "自定义录入项", "色板图片", "成分", "详情图片", "商品相关图"]
    let imagePickerVC = UIImagePickerController()

    let helper = MaterialHelper()
    var topStyle: MaterialStyle!
    var nextStyle: MaterialStyle!
    var image: UIImage!
    var selectedRow: IndexPath!

    weak var delegate: CreateItemDelegate?

    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.keyboardDismissMode = .onDrag
        tableView.rowHeight = 60
        tableView.register(UINib(nibName: "TextCell", bundle: nil), forCellReuseIdentifier: "TextCell")
        tableView.register(UINib(nibName: "ChooseCell", bundle: nil), forCellReuseIdentifier: "ChooseCell")
        tableView.register(UINib(nibName: "AddLineCell", bundle: nil), forCellReuseIdentifier: "AddLineCell")
        tableView.register(UINib(nibName: "ColorCell", bundle: nil), forCellReuseIdentifier: "ColorCell")
        tableView.register(UINib(nibName: "ComponentCell", bundle: nil), forCellReuseIdentifier: "ComponentCell")
        tableView.register(UINib(nibName: "OneImageCell", bundle: nil), forCellReuseIdentifier: "OneImageCell")
        tableView.register(UINib(nibName: "ImageCell", bundle: nil), forCellReuseIdentifier: "ImageCell")
    }


    @IBAction func cancelButtonTapped(_ button: UIButton!) {
        self.dismiss(animated: true, completion: nil)
    }

    @IBAction func doneButtonTapped(_ button: UIButton!) {
        var material = CodableMaterial(classId: classId)
        let sectionZero = listsValue[0].flatMap { $0.nilIfEmpty }
        guard sectionZero.count == 4 else {
            print(sectionZero)
            return
        }
        material.name = sectionZero[0]
        material.no = sectionZero[1]
        material.price = Double(string: sectionZero[2])!
        material.unit = sectionZero[3]
        guard nextStyle != nil else {
            return
        }
        material.styleId = nextStyle.id

        let userDefineValues = listsValue[1].flatMap { $0.nilIfEmpty }
        let userDefineKeys = listsTitle[1].flatMap { $0.nilIfEmpty }
        //说明没有添加自定义项
        if userDefineKeys.count == 0 {
            material.userDefine = nil
        } else {
            guard userDefineValues.count == userDefineKeys.count else {
                //说明有一些自定义项还没输入
                return
            }
            for i in 0 ..< userDefineKeys.count {
                material.userDefine?.append(CodableUserDefine(key: userDefineKeys[i], value: userDefineValues[i]))
            }
        }
        guard colorLists.count > 0, componentLists.count > 0, pictures.count > 0, materialImage != nil else {
            return
        }

        /// 创建色板图片
        SVProgressHUD.show()
        view.isUserInteractionEnabled = false
        var networkError: RequestError?
        let createPictureGroup = DispatchGroup()
        let _ = DispatchQueue.global(qos: .utility)
        DispatchQueue.concurrentPerform(iterations: colorLists.count) { (i) in
            let index = Int(i)
            createPictureGroup.enter()
            helper.createPicture(base64code: colorLists[index].picture, completeHandler: { (error, url) in
                guard error == nil else {
                    networkError = error
                    SVProgressHUD.showError(withStatus: error.debugDescription)
                    createPictureGroup.leave()
                    return
                }
                self.colorLists[i].picture = url!
                createPictureGroup.leave()
            })
        }

        material.component = componentLists

        // 创建商品相关图片
        createPictureGroup.enter()
        let materialBase64Image = convertToBase64(materialImage)!
        helper.createPicture(base64code: materialBase64Image) { (error, url) in
            guard error == nil else {
                networkError = error
                SVProgressHUD.showError(withStatus: error.debugDescription)
                createPictureGroup.leave()
                return
            }
            material.body = url!
            createPictureGroup.leave()
        }

        // 创建商品详情图片

        for i in 0 ..< pictures.count {
            createPictureGroup.enter()
            helper.createPicture(base64code: pictures[i].img, completeHandler: { (error, url) in
                guard error == nil else {
                    networkError = error
                    SVProgressHUD.showError(withStatus: error.debugDescription)
                    createPictureGroup.leave()
                    return
                }
                self.pictures[i].img = url!
                createPictureGroup.leave()
            })
        }
        //let queue = DispatchQueue(label: "CreateMaterial")
        createPictureGroup.notify(queue: DispatchQueue.main) { // 2
            if networkError == nil {
                material.color = self.colorLists
                material.picture = self.pictures
                let encoder = JSONEncoder()
                let data = try! encoder.encode(material)
                self.helper.createMaterial(data: data, completeHandler: { (error, materialId) in
                    guard error == nil else {
                        SVProgressHUD.showError(withStatus: error.debugDescription)
                        SVProgressHUD.dismiss(withDelay: 1.5)
                        self.dismiss(animated: true, completion: nil)
                        return
                    }

                    SVProgressHUD.showSuccess(withStatus: "成功")
                    SVProgressHUD.dismiss(withDelay: 1.5)
                    self.delegate?.didCreateItem(material: Material(name: material.name, productCode: material.no, materialId: materialId!, coverImage: material.body))
                    self.dismiss(animated: true, completion: nil)
                })
            }
            SVProgressHUD.dismiss(withDelay: 1.5)
        }

        //self.dismiss(animated: true, completion: nil)
    }


    @objc func cellLeftBtTapped(_ button: UIButton!) {
        SVProgressHUD.show()
        helper.getTopStyles { [weak self] (error, styles) in
            guard error == nil else {
                SVProgressHUD.showError(withStatus: error.debugDescription)
                return
            }

            let alertVC = UIAlertController(title: nil, message: nil, preferredStyle: .alert)
            for i in 0 ..< styles!.count {
                alertVC.addAlert(styles![i].name, action: { [weak self] (_) in
                    self?.topStyle = styles![i]
                    button.setTitle("\(styles![i].name)", for: .normal)
                })
            }
            self?.present(alertVC, animated: true, completion: nil)
            SVProgressHUD.dismiss(withDelay: 1.5)
        }
    }

    @objc func cellRightBtTapped(_ button: UIButton!) {
        guard topStyle != nil else {
            return
        }
        SVProgressHUD.show()
        helper.getNextStyles(from: topStyle.id) { [weak self] (error, styles) in
            guard let styles = styles else {
                SVProgressHUD.showError(withStatus: error.debugDescription)
                return
            }
            let alertVC = UIAlertController(title: nil, message: nil, preferredStyle: .alert)
            for i in 0 ..< styles.count {
                alertVC.addAlert(styles[i].name, action: { [weak self] (_) in
                    self?.nextStyle = styles[i]
                    button.setTitle("\(styles[i].name)", for: .normal)
                })
            }
            self?.present(alertVC, animated: true, completion: nil)
            SVProgressHUD.dismiss(withDelay: 1.5)
        }
    }
    // -MARK: DataSource and Delegate
    override func numberOfSections(in tableView: UITableView) -> Int {
        return listsTitle.count
    }
    override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return sectionTitles[section]
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        guard listsTitle[section].count != 0 else {
            return 1
        }
        return listsTitle[section].count
    }
    override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        if indexPath.section == 1 && indexPath.row != 0 {
            return true
        } else {
            return false
        }
    }
    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
            listsTitle[indexPath.section].remove(at: indexPath.row)
            listsValue[indexPath.section].remove(at: indexPath.row)
            tableView.beginUpdates()
            tableView.deleteRows(at: [indexPath], with: .automatic)
            tableView.endUpdates()
        }
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.section == 0 {
            if indexPath.row == 1 {
                let cell = tableView.dequeueReusableCell(withIdentifier: "ChooseCell") as! ChooseCell
                cell.leftButton.addTarget(self, action: #selector(cellLeftBtTapped(_:)), for: .touchUpInside)
                cell.rightButton.addTarget(self, action: #selector(cellRightBtTapped(_:)), for: .touchUpInside)
                return cell
            } else {
                let cell = tableView.dequeueReusableCell(withIdentifier: "TextCell") as! TextCell
                cell.titleLabel.text = listsTitle[0][indexPath.row]
                cell.textField.placeholder = placeHolder[indexPath.row]
                cell.textField.keyboardType = keyBoardTypes[indexPath.row]!
                cell.textField.delegate = self
                return cell
            }
        } else if indexPath.section == 1 {
            if indexPath.row == 0 {
                let cell = tableView.dequeueReusableCell(withIdentifier: "AddLineCell") as! AddLineCell
                return cell
            } else {
                let cell = tableView.dequeueReusableCell(withIdentifier: "TextCell") as! TextCell
                cell.titleLabel.text = listsTitle[1][indexPath.row]
                cell.textField.placeholder = "请输入相关信息"
                cell.textField.delegate = self
                return cell
            }
        } else if indexPath.section == 2 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "ColorCell") as! ColorCell
            cell.addButton.addTarget(self, action: #selector(sectionTwo(_:)), for: .touchUpInside)
            cell.delegate = self
            return cell
        } else if indexPath.section == 3 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "ComponentCell") as! ComponentCell
            cell.delegate = self
            return cell
        } else if indexPath.section == 4 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "OneImageCell") as! OneImageCell
            return cell
        } else {
            let cell = tableView.dequeueReusableCell(withIdentifier: "ImageCell") as! ImageCell
            cell.addButton.addTarget(self, action: #selector(sectionFive(_:)), for: .touchUpInside)
            cell.delegate = self
            return cell
        }
    }
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.section == 0 || indexPath.section == 1 {
            return 50
        } else if indexPath.section == 4 {
            return 200
        }
        else {
            return 110
        }
    }



    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        if indexPath.section == 1 && indexPath.row == 0 {
            let alerts = ["克重", "纱支", "手感", "产地", "下单制造周期"]
            let alertVC = UIAlertController(title: "新建条目", message: nil, preferredStyle: .alert)
            for i in 0 ..< alerts.count-1 {
                alertVC.addAlert(alerts[i], action: { [weak self] (_) in

                    self?.listsTitle[indexPath.section].append(alerts[i])
                    self?.listsValue[indexPath.section].append("")
                    tableView.beginUpdates()
                    tableView.insertRows(at: [IndexPath(row: (self?.listsTitle[indexPath.section].count)!-1, section: indexPath.section)], with: .automatic)
                    tableView.endUpdates()
                })
            }
            let customAlert = UIAlertAction(title: "自定义", style: .default, handler: { (_) in
                let TFAlertVC = UIAlertController(title: "自定义", message: nil, preferredStyle: .alert)
                TFAlertVC.addTextField(configurationHandler: { (textField) in
                    textField.placeholder = "请输入相关信息"
                })
                TFAlertVC.addAction(UIAlertAction(title: "确定", style: .default, handler: { [weak TFAlertVC] (_) in
                    guard let text = TFAlertVC?.textFields![0].text else {
                        return
                    }
                    guard text != "" else { return }
                    self.listsTitle[indexPath.section].append(text)
                    self.listsValue[indexPath.section].append("")
                    tableView.beginUpdates()
                    tableView.insertRows(at: [IndexPath(row: self.listsTitle[indexPath.section].count-1, section: indexPath.section)], with: .automatic)
                    tableView.endUpdates()
                }))
                self.present(TFAlertVC, animated: true, completion: nil)
            })
            alertVC.addAction(customAlert)
            let cancelAlert = UIAlertAction(title: "取消", style: .cancel, handler: nil)
            alertVC.addAction(cancelAlert)
            self.present(alertVC, animated: true, completion: nil)
        } else if indexPath.section == 4 && indexPath.row == 0 {
            selectedRow = indexPath
            presentImagePickerVC()
        }
    }


    // -MARK: section private methods
    /// show alert for different sections
    //section 2 -@objc  色板
    @objc func sectionTwo(_ button: UIButton!) {
        let point = button.convert(CGPoint.zero, to: tableView)
        let indexPath = tableView.indexPathForRow(at: point)
        selectedRow = indexPath!
        presentImagePickerVC()
    }


    /// 添加多张详情图片
    ///
    /// - Parameter button: nil
    @objc func sectionFive(_ button: UIButton!) {
        let point = button.convert(CGPoint.zero, to: tableView)
        let indexPath = tableView.indexPathForRow(at: point)
        selectedRow = indexPath!
        presentImagePickerVC()
    }

    /// private funcs
    private func presentImagePickerVC() {

        let alertVC = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
        imagePickerVC.allowsEditing = true
        imagePickerVC.delegate = self
        alertVC.addAction(UIAlertAction(title: "拍照", style: .default, handler: { (_) in
            self.imagePickerVC.sourceType = .camera
            self.present(self.imagePickerVC, animated: true, completion: nil)
        }))
        alertVC.addAction(UIAlertAction(title: "本地图片", style: .default, handler: { (_) in
            self.imagePickerVC.sourceType = .photoLibrary
            self.present(self.imagePickerVC, animated: true, completion: nil)
        }))
        alertVC.addAction(UIAlertAction(title: "取消", style: .cancel, handler: nil))
        self.present(alertVC, animated: true, completion: nil)
    }
}

extension CreateItemVC: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        if let image = info[UIImagePickerControllerEditedImage] as? UIImage {
            dismiss(animated: true, completion: {
                if self.selectedRow.section == 2 {
                    let cell = self.tableView.cellForRow(at: self.selectedRow) as! ColorCell
                    cell.showAlert(image: image)
                } else if self.selectedRow.section == 4 {
                  let cell = self.tableView.cellForRow(at: self.selectedRow) as! OneImageCell
                    self.materialImage = image
                    cell.imgView.image = image
                } else if self.selectedRow.section == 5 {
                    let cell = self.tableView.cellForRow(at: self.selectedRow) as! ImageCell
                    cell.images.append(image)
                    cell.addImage()
                }
            })
        }
    }
}

extension CreateItemVC: UITextFieldDelegate {
    func textFieldDidBeginEditing(_ textField: UITextField) {

    }
    func textFieldDidEndEditing(_ textField: UITextField) {
        let point = textField.convert(CGPoint.zero, to: tableView)
        guard let indexPath = tableView.indexPathForRow(at: point) else {
            return
        }
        let section = indexPath.section
        let row = indexPath.row
        guard let text = textField.text else {
            return
        }
        listsValue[section][row] = text
        print(listsValue)
    }
}

extension CreateItemVC: ColorCellDelegate {
    func insertColor(color: CodableColorOfMaterial) {
        colorLists.append(color)
    }
    func deleteColor(at index: Int) {
        colorLists.remove(at: index)
    }
}

extension CreateItemVC: ComponentCellDelegate {
    func insertComponent(component: CodableComponentOfMaterial) {
        componentLists.append(component)
    }
    func deleteComponent(at index: Int) {
        componentLists.remove(at: index)
    }
}

extension CreateItemVC: ImageCellDelegate {
    func insert(image: CodablePictureOfMaterial) {
        pictures.append(image)
    }
    func deleteImage(at index: Int) {
        pictures.remove(at: index)
    }
}
